﻿
namespace LS.Nc6.Application.Cms
{
    /// <summary>
    /// 栏目接口
    /// </summary>
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [ApiDescriptionSettings("CMS")]
    public class ChannelService : IDynamicApiController
    {
        private readonly ISysUserService _userService;

        private readonly IHttpContextAccessor _httpContextAccessor;

        private readonly IEventPublisher _eventPublisher;

        private readonly ISysConfigurationService _configurationService;

        private readonly ICmsChannelService _channelService;

        private readonly ISysFileService _fileService;

        private readonly ICache _cache;

        private readonly ICmsChannelGroupService _cmsChannelGroupService;
        public ChannelService(ISysUserService userService, IEventPublisher eventPublisher, ISysConfigurationService configurationService, IHttpContextAccessor httpContextAccessor, 
            ICmsChannelService channelService, ISysFileService sysFileService, ICmsChannelGroupService cmsChannelGroupService,
            IOptions<CacheOptions> cacheOptions, Func<string, ISingleton, object> resolveNamed)
        {
            _userService = userService;
            _httpContextAccessor = httpContextAccessor;
            _eventPublisher = eventPublisher;
            _configurationService = configurationService;
            _channelService = channelService;
            _cache = resolveNamed(cacheOptions.Value.CacheType.ToString(), default) as ICache;
            _fileService = sysFileService;
            _cmsChannelGroupService = cmsChannelGroupService;
        }

        /// <summary>
        /// 获取栏目分组
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/channel/group")]
        public async Task<List<ChannelGroupOutput>> GetChannelGroup()
        {
            var result = await _cmsChannelGroupService.List(a =>true,a=>a.Taxis);
            var datalist = result.Adapt<List<ChannelGroupOutput>>();
            return datalist;
        }

        /// <summary>
        /// 获取全部栏目Tree格式返回
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/channel/tree")]
        public async Task<List<ChannelTreeOutput>> GetChannelTree()
        {
            List<ChannelTreeOutput> lsetm = new List<ChannelTreeOutput>();
            if (_cache.Get<List<ChannelTreeOutput>>("ApiChannelData") != null && _cache.Get<List<ChannelTreeOutput>>("ApiChannelData").Count > 0)
            {
                lsetm = _cache.Get<List<ChannelTreeOutput>>("ApiChannelData");
            }
            else
            {
                List<CmsChannelEntity> channellist = await _channelService.List(a => true, a => a.Taxis);
                if (channellist != null)
                {
                    var channelhomelist = channellist.Where(w => w.ParentId == 0);
                    foreach (var item in channelhomelist)
                    {
                        ChannelTreeOutput etm = new ChannelTreeOutput();
                        etm.Id = item.Id;
                        etm.Name = item.ChannelName;
                        etm.IndexName = item.IndexName;
                        GetChildren(etm, channellist, item.Id);
                        lsetm.Add(etm);
                    }
                }
                await _cache.SetAsync("ApiChannelData", lsetm);
            }
            return lsetm;
        }


        /// <summary>
        /// 获取指定栏目下面所有子集Tree格式返回
        /// </summary>
        /// <param name="channelId">栏目id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/channel/treeChild")]
        public async Task<List<ChannelTreeOutput>> GetChannelChildTree([Required]long channelId)
        {
            List<ChannelTreeOutput> lsetm = new List<ChannelTreeOutput>();

            if (channelId < 1)
            {
                throw Oops.Oh("参数channelId 不能为空");
            }
            List<CmsChannelEntity> channellist = await _channelService.List(a => true, a => a.Taxis);
            if (channellist != null)
            {
                var channelhomelist = channellist.Where(w => w.Id == channelId);
                foreach (var item in channelhomelist)
                {
                    ChannelTreeOutput etm = new ChannelTreeOutput();
                    etm.Id = item.Id;
                    etm.Name = item.ChannelName;
                    etm.IndexName = item.IndexName;
                    GetChildren(etm, channellist, item.Id);
                    lsetm.Add(etm);
                }
            }
            return lsetm;
        }

        /// <summary>
        /// 获取子集栏目(只获一级子集)
        /// </summary>
        /// <param name="channelId">栏目Id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/channel/childList")]
        public async Task<List<ChannelChildOutput>> GetChannelChildList([Required] long channelId)
        {
            List<ChannelChildOutput> lsetm = new List<ChannelChildOutput>();
            if (_cache.Get<List<ChannelChildOutput>>("ApiChannelChildData") != null && _cache.Get<List<ChannelChildOutput>>("ApiChannelChildData").Count > 0)
            {
                lsetm = _cache.Get<List<ChannelChildOutput>>("ApiChannelChildData");
            }
            else
            {
                List<long> channellist = await _channelService.GetChannelIdsAsync(channelId,2);
                if (channellist.Count>0)
                {
                    var channelhomelist = await _channelService.List(a => channellist.Contains(a.Id),a=>a.Id);
                    foreach (var item in channelhomelist)
                    {
                        ChannelChildOutput etm = new ChannelChildOutput();
                        etm.Id = item.Id;
                        etm.Name = item.ChannelName;
                        etm.IndexName = item.IndexName;
                        lsetm.Add(etm);
                    }
                }
                await _cache.SetAsync("ApiChannelChildData", lsetm);
            }
            return lsetm;
        }

        /// <summary>
        /// 根据分组获取栏目
        /// </summary>
        /// <param name="groupName">栏目分组名称</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/channel/ListByGroupName")]
        public async Task<List<ChannelModelOutPut>> GetListByGroupName([Required] string groupName)
        {
            if (string.IsNullOrEmpty(groupName))
            {
                throw Oops.Oh("参数栏目groupName 不能为空");
            }
            var result = await _channelService.List(a => a.GroupNames.Contains (groupName), a => a.Id);
            List<ChannelModelOutPut> channellist = new List<ChannelModelOutPut>();
            
            for (int i = 0; i < result.Count; i++)
            {
                var channelmodel = result[i];
                var channeloutput = channelmodel.Adapt<ChannelModelOutPut>();
                var filelist = await _fileService.CustomerFileList(channelmodel.ImageUrlIds);
                var urllist = new List<string>();
                foreach (var file in filelist)
                {
                    //urllist.Add(App.HttpContext.Request.Host.ToString()+file["fpath"]);
                    urllist.Add(file["fpath"].ToString());
                }
                channeloutput.ImageUrls = urllist;
                channellist.Add(channeloutput);
            }
            
            return channellist;
        }

        /// <summary>
        /// 获取栏目详情(栏目Id)
        /// </summary>
        /// <param name="id">栏目id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/channel/detail")]
        public async Task<ChannelModelOutPut> GetModel([Required] long id)
        {
            var model = await _channelService.GetByIdAsync(id);
            ChannelModelOutPut channelmodel = model.Adapt<ChannelModelOutPut>();
            var filelist =await _fileService.CustomerFileList(model.ImageUrlIds);
           var urllist = new List<string>();
            foreach (var file in filelist)
            {
                //urllist.Add(App.HttpContext.Request.Host.ToString()+file["fpath"]);
                urllist.Add(file["fpath"].ToString());
            }
            channelmodel.ImageUrls = urllist;
            return  channelmodel;
        }
        
        /// <summary>
        /// 获取栏目详情(indexName)
        /// </summary>
        /// <param name="indexName">栏目indexname</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/channel/detailByIndexName")]
        public async Task<ChannelModelOutPut> GetModelByIndexName([Required] string indexName)
        {
            if(string.IsNullOrEmpty(indexName))
            {
                throw Oops.Oh("参数栏目IndexName 不能为空");
            }
            var result = await _channelService.List(a=>a.IndexName == indexName,a=>a.Id);
            CmsChannelEntity model =new CmsChannelEntity ();
            if (result!=null && result.First() != null)
            {
                model = result.First();
            }
            ChannelModelOutPut channelmodel = model.Adapt<ChannelModelOutPut>();
            var filelist = await _fileService.CustomerFileList(model.ImageUrlIds);
            var urllist = new List<string>();
            foreach (var file in filelist)
            {
                //urllist.Add(App.HttpContext.Request.Host.ToString()+file["fpath"]);
                urllist.Add(file["fpath"].ToString());
            }
            channelmodel.ImageUrls = urllist;
            return channelmodel;
        }

        /// <summary>
        /// 添加栏目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("api/channel/add")]
        public async Task<long> SaveChannel([FromBody] CmsChannelAddInput input)
        {
            var model = input.Adapt<CmsChannelEntity>();
            if (model.ParentId < 1)
            {
                throw Oops.Oh("参数父栏目Id 不能为空");
            }
            var parentChannel = await _channelService.GetByIdAsync(model.ParentId.Value);
            if (parentChannel != null)
            {
                model.ParentsPath = parentChannel.ParentsPath == null
                    ? parentChannel.Id.ToString()
                    : parentChannel.ParentsPath + "," + parentChannel.Id.ToString();

                model.ParentsCount = parentChannel.ParentsCount + 1;

                var maxTaxis = await _channelService.GetMaxTaxis(model.ParentId.Value);
                if (maxTaxis == 0)
                {
                    maxTaxis = parentChannel.Taxis.Value;
                }
                model.Taxis = maxTaxis + 1;
            }
            else
            {
                model.Taxis = 1;
            }
            model.ChildrenCount = 0;

            var linktype =(LinkType) Enum.Parse(typeof(LinkType), input.LinkType);
            
            model.LinkType = linktype.ToString();

            long channelId = await _channelService.InsertAsync(model);

            return channelId;
        }

        #region 私有方法
        private void GetChildren(ChannelTreeOutput etm, List<CmsChannelEntity> listpartmenu, long pid)
        {
            var children = listpartmenu.Where(w => w.ParentId == pid);
            List<ChannelTreeOutput> lsetm = new List<ChannelTreeOutput>();
            if (children != null && children.Count() > 0)
            {
                foreach (var item in children)
                {
                    ChannelTreeOutput etmchildren = new ChannelTreeOutput();
                    etmchildren.Id = item.Id;
                    etmchildren.Name = item.ChannelName;
                    etmchildren.IndexName = item.IndexName;
                    GetChildren(etmchildren, listpartmenu, item.Id);
                    lsetm.Add(etmchildren);
                }
                if (lsetm.Count > 0)
                {
                    etm.Children = lsetm;
                }
            }
        }


        #endregion

    }
}
